﻿using SD.ContentSystem.Domain.Entities;
using SD.ContentSystem.Domain.IRepositories.Interfaces;
using SD.Infrastructure.Repository.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace SD.ContentSystem.Repository.Implements
{
    /// <summary>
    /// 相片仓储实现
    /// </summary>
    public class PhotoRepository : EFAggRootRepositoryProvider<Photo>, IPhotoRepository
    {
        #region # 根据条件获取实体对象集合（默认排序） —— override IOrderedQueryable<Photo> FindBySort(...
        /// <summary>
        /// 根据条件获取实体对象集合（默认排序）
        /// </summary>
        /// <returns>实体对象集合</returns>
        protected override IOrderedQueryable<Photo> FindBySort(Expression<Func<Photo, bool>> condition)
        {
            return base.Find(condition).OrderBy(x => x.Sort).ThenByDescending(x => x.AddedTime);
        }
        #endregion

        #region # 根据相册获取相片列表 —— IEnumerable<Photo> FindByAlbum(string photoAlbumNo)
        /// <summary>
        /// 根据相册获取相片列表
        /// </summary>
        /// <param name="photoAlbumNo">相册编号</param>
        /// <returns>相片列表</returns>
        public IEnumerable<Photo> FindByAlbum(string photoAlbumNo)
        {
            Expression<Func<Photo, bool>> condition =
                x =>
                    (string.IsNullOrEmpty(photoAlbumNo) || x.PhotoAlbumNo == photoAlbumNo);

            return base.FindBySort(condition).AsEnumerable();
        }
        #endregion

        #region # 分页获取相片列表 —— IEnumerable<Photo> FindByPage(string keywords, string photoAlbumNo...
        /// <summary>
        /// 分页获取相片列表
        /// </summary>
        /// <param name="keywords">关键字</param>
        /// <param name="photoAlbumNo">相册编号</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="rowCount">总记录条数</param>
        /// <param name="pageCount">总页数</param>
        /// <returns>相片列表</returns>
        public IEnumerable<Photo> FindByPage(string keywords, string photoAlbumNo, int pageIndex, int pageSize, out int rowCount, out int pageCount)
        {
            Expression<Func<Photo, bool>> condition =
                x =>
                    (string.IsNullOrEmpty(keywords) || x.Keywords.Contains(keywords)) &&
                    (string.IsNullOrEmpty(photoAlbumNo) || x.PhotoAlbumNo == photoAlbumNo);

            return base.FindByPage(condition, pageIndex, pageSize, out rowCount, out pageCount).AsEnumerable();
        }
        #endregion

        #region # 相册下是否存在相片 —— bool ExistsByAlbum(string albumNo)
        /// <summary>
        /// 相册下是否存在相片
        /// </summary>
        /// <param name="albumNo">相册编号</param>
        /// <returns>是否存在</returns>
        public bool ExistsByAlbum(string albumNo)
        {
            return base.Exists(x => x.PhotoAlbumNo == albumNo);
        }
        #endregion
    }
}
